<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { Iphone, Lock, Key } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import { useCommonStoreHook } from '@/store/modules/common'

import {
  _login,
  _sentCaptcha,
  _createKey,
  _createQr,
  _checkQr,
  _loginStatus
} from '@/service/user'

const commonStore = useCommonStoreHook()
let timer = null
let checkTimer = null

const visible = ref(false)
const show = async () => {
  if (loginInfo.value.loginType === 'qr') {
    await qrLogin()
  }
  visible.value = true
}
const handleClose = () => {
  visible.value = false
  clearInterval(timer)
  clearInterval(checkTimer)
}
defineExpose({
  show
})

const qrLogin = () => {
  return new Promise((resolve, reject) => {
    _createKey().then(async (res) => {
      loginInfo.value.uniKey = res.data.unikey
      console.log(loginInfo.value.uniKey, res)
      const qrData = await _createQr({
        key: loginInfo.value.uniKey,
        qrimg: true
      })
      loginInfo.value.qrSrc = qrData.data.qrimg
      _checkTimer()
      resolve(res)
    })
  })
}

const _checkTimer = () => {
  checkTimer = setInterval(() => {
    _checkQr({ key: loginInfo.value.uniKey }).then((res) => {
      console.log(res)
      if (res.code === 800) {
        ElMessage.warning('二维码已过期,请重新获取')
        clearInterval(timer)
      }
      if (res.code === 803) {
        clearInterval(checkTimer)
        localStorage.setItem('cookie', res.cookie)
        commonStore.cookie = res.cookie
        getLoginStatus(res.cookie)
      }
    })
  }, 3000)
}

const getLoginStatus = (cookie: string) => {
  _loginStatus({ cookie }).then((res) => {
    loginInfo.value.LoginStatus = true
    localStorage.setItem('account', JSON.stringify(res.data.account))
    localStorage.setItem('profile', JSON.stringify(res.data.profile))
    commonStore.account = res.data.account
    commonStore.profile = res.data.profile
    setTimeout(() => {
      handleClose()
    }, 1000)
  })
}

const loginInfo = ref({
  loginType: 'qr',
  phone: '',
  password: '',
  captcha: '',
  second: 0,
  isChecked: false,
  uniKey: '',
  qrSrc: '',
  LoginStatus: false
})

const loginFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  phone: [{ required: true, message: '请输入手机号', trigger: 'change' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'change' }]
})
const sentCaptcha = () => {
  if (!loginInfo.value.phone) return ElMessage('请输入手机号')
  const regg =
    /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
  if (!regg.test(loginInfo.value.phone)) return ElMessage('请输入正确的手机号')
  _sentCaptcha({ phone: loginInfo.value.phone })
    .then(() => {
      ElMessage.success('发送成功')
      loginInfo.value.second = 59
      timer = setInterval(() => {
        if (loginInfo.value.second === 0) {
          clearInterval(timer)
        }
        loginInfo.value.second -= 1
      }, 1000)
    })
    .catch((err) => {
      ElMessage.success(err)
    })
}

const login = () => {
  if (!loginInfo.value.isChecked)
    return ElMessage.warning(
      '请勾选同意《服务条款》《隐私条款》《儿童隐私协议》'
    )
  loginFormRef.value.validate((valid) => {
    if (valid) {
      const params = {
        phone: loginInfo.value.phone,
        password: loginInfo.value.password,
        captcha: loginInfo.value.captcha
      }

      _login(params).then((res) => {
        localStorage.setItem('account', JSON.stringify(res.data.account))
        localStorage.setItem('profile', JSON.stringify(res.data.profile))
        commonStore.account = res.data.account
        commonStore.profile = res.data.profile
        ElMessage.success('登陆成功')
        visible.value = false
      })
    }
  })
}

const changeLoginType = (type: string) => {
  loginInfo.value.loginType = type
  clearInterval(checkTimer)
  type === 'qr' && qrLogin()
}
</script>

<template>
  <el-dialog v-model="visible" width="400" :before-close="handleClose">
    <template #header>
      <div class="my-header">
        <div
          v-show="loginInfo.loginType !== 'qr'"
          class="qr_back"
          @click="changeLoginType('qr')"
        >
          <img src="../../assets/img/qr.jpg" alt="" />
          <div class="qr_change"></div>
        </div>
      </div>
    </template>
    <template v-if="loginInfo.loginType !== 'qr'">
      <div class="logo icon-wangyiyunyinle"></div>
      <el-form
        style="margin-top: 40px"
        ref="loginFormRef"
        :model="loginInfo"
        :rules="rules"
        status-icon
      >
        <el-form-item prop="phone">
          <el-input
            size="large"
            v-model="loginInfo.phone"
            placeholder="请输入手机号"
            maxlength="11"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="captcha" v-if="loginInfo.loginType === 'cpt'">
          <el-input
            size="large"
            v-model="loginInfo.captcha"
            placeholder="请输入验证码"
            maxlength="6"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><Key /></el-icon>
            </template>
            <template #append>
              <el-button
                style="width: 120px"
                link
                :disabled="loginInfo.second > 0"
                @click="sentCaptcha"
                >{{
                  loginInfo.second > 0
                    ? `(${loginInfo.second}s后重新获取)`
                    : '获取验证码'
                }}</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password" v-else>
          <el-input
            size="large"
            v-model="loginInfo.password"
            placeholder="请输入密码"
            type="password"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <div>
        <el-button type="primary" link>密码登录</el-button>
      </div>

      <el-button
        class="login_button"
        color="#ec4141"
        size="large"
        @click="login"
        >登录</el-button
      >

      <div class="login_logo">
        <i class="icon-weixin" style="background-color: #02de6c"></i>
        <i class="icon-QQ" style="background-color: #409eff"></i>
        <i class="icon-weibo"></i>
        <i class="icon-wangyi"></i>
      </div>

      <el-checkbox
        style="margin-top: 30px"
        v-model="loginInfo.isChecked"
        :label="true"
        size="small"
      >
        同意
        <span class="primary">《服务条款》</span>
        <span class="primary">《隐私条款》</span>
        <span class="primary">《儿童隐私协议》</span>
      </el-checkbox>
    </template>
    <template v-else>
      <div class="qr_box">
        <div class="qr_title">扫码登录</div>

        <div class="qr_image">
          <img :src="loginInfo.qrSrc" alt="" @click="qrLogin" />
          <div class="status_success" v-show="loginInfo.LoginStatus">
            <i class="icon-dengluchenggong"></i>
            <span>授权成功</span>
          </div>
        </div>
        <p>
          使用
          <span style="color: var(--music-base-color)">网易云音乐APP</span>
          扫码登录
        </p>
        <el-button style="margin-top: 60px" link @click="changeLoginType('cpt')"
          >选择其他登陆方式 ></el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.logo {
  width: 60px;
  margin: 0 auto;
  color: $red;
  font-size: 60px;
}
.login_button {
  width: 100%;
  margin-top: 40px;
  color: #fff;
}
.primary {
  color: #409eff;
}

.login_logo {
  display: flex;
  justify-content: space-between;
  margin-top: 40px;
  i {
    padding: 10px;
    border-radius: 50%;
    font-size: 18px;
    color: #fff;
    background-color: $red;
    cursor: pointer;
  }
}

.qr_box {
  text-align: center;
  .qr_image {
    position: relative;
    width: 180px;
    height: 180px;
    margin: 30px auto;
    .status_success {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 180px;
      height: 180px;
      position: absolute;
      top: 0%;
      left: 0%;
      font-weight: bold;
      z-index: 99;
      background-color: rgba(0, 0, 0, 0.8);
      span {
        color: $red;
        font-size: 20px;
      }
      i {
        color: $red;
        font-size: 24px;
      }
    }
  }
  .qr_title {
    margin-top: 60px;
    font-size: 20px;
  }
}

:deep(.el-dialog__header) {
  position: relative;
}
.my-header {
  img {
    width: 60px;
    height: auto;
    position: absolute;
    top: 10px;
    left: 10px;
  }
}
.qr_back {
  position: absolute;
  width: 80px;
  height: 80px;
  top: 0;
  left: 0;
  background-color: var(--el-color-primary-light-9);
  cursor: pointer;
}
.qr_change {
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  border-color: transparent transparent var(--el-bg-color) transparent;
  border-style: solid;
  border-width: 0 0 80px 80px;
}
</style>

<style>
.el-dialog__body {
  padding: 20px 50px 40px;
}
</style>
